//
//  HomeViewController.m
//
//
//  Created by chris on 15/12/26.
//
//

#import "HomeViewController.h"
#import "FunctionView.h"
#import "InquiryView.h"
#import "OrderVc.h"
#import "RollingLabel.h"
#import "LoginViewController.h"
#import "UserModel.h"
#import "AppDelegate.h"
#import "DataModel.h"
#import "NoticeDetailVc.h"
#import "NumPoolManageVc.h"
#import "MsgVc.h"
#import "UIView+Extension.h"
#import "Macro.h"
#import "StoresViewController.h"
#import "StoresListViewController.h"
#import "PersonalCenterVc.h"
#import "BackgroundBizVc.h"

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,FunctionViewDelegate,InquiryViewDelegate>
@property(nonatomic , strong)UIView * rollParentView;
@property(nonatomic , strong)UITableView * tableview;
@property(nonatomic , strong)RollingLabel * rollLa;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"和掌柜";
    [super.leftButton removeAllSubViews];
    _rollParentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 40)];
    _rollLa = [[RollingLabel alloc]initWithFrame:CGRectMake(10, 13, DEF_SCREEN_WIDTH-20, 14)];
    [_rollLa initWithArray:@[@"公告1",@"公告2"]];
    [_rollLa start];
    [_rollParentView addSubview:_rollLa];

    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
    [_rollParentView addGestureRecognizer:tap];

    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableview.delegate = self;
    _tableview.scrollEnabled = NO;
    _tableview.sectionHeaderHeight = 0;
    _tableview.sectionFooterHeight = 0;
    _tableview.dataSource = self;
    _tableview.tableHeaderView = _rollParentView;
    _tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self addSubview:_tableview];

    UserModel *model= [[AppDelegate appDelegate] getUserInfo];
    if (model && model.username.length != 0 && model.pwd.length != 0) {
        //自动登陆
        [[AppDelegate appDelegate] autologinAction:model];
    }else{
        [[AppDelegate appDelegate] toLogin];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSucess) name:DEFN_LOGIN_SUCESS object:nil];
    [self addLogoutButton];
}

- (void) loginSucess {
    UserModel *userModel = [[AppDelegate appDelegate] getUserInfo];
    //刷新公告
    [_rollLa removeFromSuperview];
    _rollLa = nil;
    _rollLa = [[RollingLabel alloc]initWithFrame:CGRectMake(10, 13, DEF_SCREEN_WIDTH-20, 14)];
    NoticePage *noticePage = userModel.noticePage;
    NSMutableArray *noticeArr = noticePage.data;//NoticePageObject
    if (noticePage && noticeArr) {
        [_rollLa initWithArray:noticePage.dataNameArra];
    } else {
        [_rollLa initWithArray:@[@""]];
    }
    [_rollLa start];
    [_rollParentView addSubview:_rollLa];

    long long pendingBlackNum = userModel.pendingBlackNum.longLongValue;//后台业务待处理条数
    if (pendingBlackNum >= 1) {
        DLog(@"发起本地通知.....");
        [self createUILocalNotification];
    }
    //刷新门店签约数量和工单处理数量
    [self.tableview reloadData];
}

/**
 * 创建本地的通知
 * 1:要申请权限
 */
- (void) createUILocalNotification {
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    //设置本地通知的触发时间（如果要立即触发，无需设置），这里设置为2s后
    NSDate *now=[NSDate new];
    localNotification.fireDate=[now dateByAddingTimeInterval:2];//2秒后通知

    //设置本地通知的时区
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    //设置通知的内容
    localNotification.alertBody = [NSString stringWithFormat:@"你有未处理的业务"];

    //设置通知动作按钮的标题
    localNotification.alertAction = @"查看";
    //设置提醒的声音，可以自己添加声音文件，这里设置为默认提示声
    localNotification.soundName = UILocalNotificationDefaultSoundName;

    //设置通知的相关信息，这个很重要，可以添加一些标记性内容，方便以后区分和获取通知的信息
    //NSDictionary *infoDic = [NSDictionary dictionaryWithObjectsAndKeys:nil,@"remindDate", nil];
    //localNotification.userInfo = infoDic;
    //在规定的日期触发通知
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

- (void) addLogoutButton {
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0 , 0, 40 ,40)];
//    button.backgroundColor = [UIColor redColor];
    button.titleLabel.font = font(15);
    [button setTitle:@"" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"group_detail"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(logoutInHome) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = leftItem;
//    [self.view addSubview:button];
}

#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"home";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    if (indexPath.section == 0)
    {
        //功能模块
        FunctionView * function = [[FunctionView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (DEF_SCREEN_HEIGHT-44-40*2-64)*3/4)];
        UserModel *userModel = [[AppDelegate appDelegate] getUserInfo];
        NSInteger pendingOrderNum   = userModel.pendingOrderNum.integerValue;//待处理工单数
        NSInteger pendingWebstieNum = userModel.pendingWebstieNum.integerValue; //待处理门店签约数
        NSInteger pendingBlackNum   = userModel.pendingBlackNum.integerValue; //待处理门店签约数
        function.pendingOrderNum    = pendingOrderNum;
        function.pendingWebstieNum  = pendingWebstieNum;
        function.pendingBlackNum    = pendingBlackNum;
        [function drawMySubvies];
        function.delegate = self;
        [cell.contentView removeAllSubViews];
        [cell.contentView addSubview:function];
    }
    else
    {
        //查询模块
        InquiryView * inquiry = [[InquiryView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (DEF_SCREEN_HEIGHT-44-40*2-64)*1/4)];
        inquiry.delegate = self;
        [cell.contentView addSubview:inquiry];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark-UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return (DEF_SCREEN_HEIGHT-44-40*2-64)*3/4;
    }
    return (DEF_SCREEN_HEIGHT-44-40*2-64)*1/4;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    label.backgroundColor = [UIColor colorWithRed:0 green:0.63 blue:0.97 alpha:1];
    label.font = font(15);
    label.textColor = [UIColor whiteColor];
    if (section == 0)
    {
        label.text = @"  功能模块";
    }
    else
    {
        label.text = @"  查询模块";
    }
    return label;
}
#pragma mark-FunctionViewDelegate
- (void)clickWithIndex:(int)index
{
    NSLog(@"%d",index);
    switch (index)
    {
        case 0://门店管理
        {
            StoresViewController *stores=[[StoresViewController alloc]init];
            [self.navigationController pushViewController:stores animated:YES];
        }
            break;
        case 1://工单处理
        {
            OrderVc * order = [[OrderVc alloc]init];
            [self.navigationController pushViewController:order animated:YES];

        }
            break;
        case 2://号池管理
        {
            NumPoolManageVc * numPoolManageVc = kHome_storyVCName(@"NumPoolManageVc");
            [self.navigationController pushViewController:numPoolManageVc animated:YES];
        }
            break;
        case 3://消息管理
        {
            MsgVc * msgVc = kHome_storyVCName(@"MsgVc");
            [self.navigationController pushViewController:msgVc animated:YES];
        }
            break;
        case 4://后台业务管理
        {
            BackgroundBizVc * bizVc = [[BackgroundBizVc alloc] init];
            [self.navigationController pushViewController:bizVc animated:YES];
        }
            break;

        default:
            break;
    }
}
#pragma mark-InquiryViewDelegate
- (void)inClickWithIndex:(int)index
{
    if (index == 0)
    {
        DLog(@"信息管理");
        StoresListViewController * list = [[StoresListViewController alloc]init];
        [self.navigationController pushViewController:list animated:YES];
    } else {
        DLog(@"工单管理/列表");
        OrderVc * order = [[OrderVc alloc]init];
        order.isFromList = YES;
        [self.navigationController pushViewController:order animated:YES];
    }
}

#pragma mark-event
- (void)tapClick
{
    NSLog(@"home RollingLabel = %d",self.rollLa.num);
    UserModel *userModel = [[AppDelegate appDelegate] getUserInfo];
    NoticePage *noticePage = userModel.noticePage;
    NoticePageObject *noticePageObject =  noticePage.data[self.rollLa.num < 0 ? 0 : self.rollLa.num];
    NSLog(@"rollingLableWithIndex:%@", noticePageObject.title);

    NoticeDetailVc *noticeDetailVc=[[NoticeDetailVc alloc]initWithNibName:@"NoticeDetailVc" bundle:nil];
    noticeDetailVc.noticePageObject = noticePageObject;
    [self.navigationController pushViewController:noticeDetailVc animated:YES];
}

//退出登陆更改为跳转简单版个人页面
- (void) logoutInHome{
    PersonalCenterVc *vc = [[PersonalCenterVc alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
